/**
 * 
 */
package com.adsanse.vipul;

import java.io.IOException;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

/**
 * @author Evan
 * AuthHelper retrieves authentication information about the user logged on the Android device
 */
public class AuthHelper
{
	private static final String TAG = "AuthHelper";
	
	/**
	 * Retrieves all of the Google accounts on the device
	 * @param context
	 * @return
	 */
	public Account[] getAccounts(Context context)
	{
		return AccountManager.get(context).getAccountsByType("com.google");
	}
	
	public String getRefreshedAuthToken(Context context, String name, Activity activity, String token)
	{
		String retVal = "";
		Account account = new Account(name, "com.google");
		AccountManager.get(context).invalidateAuthToken("com.google", token);
		
		AccountManagerFuture<Bundle> accFut = AccountManager.get(context).getAuthToken(account, "reader", null, activity, null, null);
		try
		{
			 Bundle authTokenBundle = accFut.getResult();
			 retVal = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();			 
		} 
		catch (OperationCanceledException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (AuthenticatorException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return retVal;
	}
	
	public String getAuthToken(Context context, String name, Activity activity)
	{
		String retVal = "";
		Account account = new Account(name, "com.google");
		AccountManagerFuture<Bundle> accFut = AccountManager.get(context).getAuthToken(account, "ah", null, activity, null, null);
		try
		{
			 Bundle authTokenBundle = accFut.getResult();
			 retVal = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();			 
		} 
		catch (OperationCanceledException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (AuthenticatorException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return retVal;
	}

}
